<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="审批人id" prop="approverId">
        <el-input
          v-model="queryParams.approverId"
          placeholder="请输入审批人id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审批人" prop="approverName">
        <el-input
          v-model="queryParams.approverName"
          placeholder="请输入审批人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="下一个审核人id" prop="nextApproverId">
        <el-input
          v-model="queryParams.nextApproverId"
          placeholder="请输入下一个审核人id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="下一个审核人" prop="nextApprover">
        <el-input
          v-model="queryParams.nextApprover"
          placeholder="请输入下一个审核人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="业务id" prop="bussniessId">
        <el-input
          v-model="queryParams.bussniessId"
          placeholder="请输入业务id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="当前操作步骤描述" prop="currentStep">
        <el-input
          v-model="queryParams.currentStep"
          placeholder="请输入当前操作步骤描述"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="下一步操作描述" prop="nextStep">
        <el-input
          v-model="queryParams.nextStep"
          placeholder="请输入下一步操作描述"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核步骤" prop="stepNo">
        <el-input
          v-model="queryParams.stepNo"
          placeholder="请输入审核步骤"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:record:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:record:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:record:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:record:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" width="80">
        <template #default="scope">
          {{ total - (queryParams.pageNum - 1) * queryParams.pageSize - scope.$index }}
        </template>
      </el-table-column>
      <el-table-column label="审批意见" align="center" prop="opinion" />
      <el-table-column label="审批类型(1:退住,2:请假,3:入住)" align="center" prop="type" />
      <el-table-column label="完成时间" align="center" prop="finishTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.finishTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审批人id" align="center" prop="approverId" />
      <el-table-column label="审批人" align="center" prop="approverName" />
      <el-table-column label="审批人角色" align="center" prop="approverNameRole" />
      <el-table-column label="下一个审核人id" align="center" prop="nextApproverId" />
      <el-table-column label="下一个审核人" align="center" prop="nextApprover" />
      <el-table-column label="下一个审核人角色" align="center" prop="nextApproverRole" />
      <el-table-column label="业务id" align="center" prop="bussniessId" />
      <el-table-column label="当前操作步骤描述" align="center" prop="currentStep" />
      <el-table-column label="下一步操作描述" align="center" prop="nextStep" />
      <el-table-column label="审核状态(1:通过,2:拒绝,3:驳回,4:撤回,5:撤销)" align="center" prop="auditStatus" />
      <el-table-column label="审核步骤" align="center" prop="stepNo" />
      <el-table-column label="处理类型" align="center" prop="handleType" />
      <el-table-column label="额外字段1" align="center" prop="extraField1" />
      <el-table-column label="额外字段2" align="center" prop="extraField2" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
           <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:record:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:record:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改审批记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="recordRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="审批意见" prop="opinion">
          <el-input v-model="form.opinion" placeholder="请输入审批意见" />
        </el-form-item>
        <el-form-item label="完成时间" prop="finishTime">
          <el-date-picker clearable
            v-model="form.finishTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择完成时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审批人id" prop="approverId">
          <el-input v-model="form.approverId" placeholder="请输入审批人id" />
        </el-form-item>
        <el-form-item label="审批人" prop="approverName">
          <el-input v-model="form.approverName" placeholder="请输入审批人" />
        </el-form-item>
        <el-form-item label="审批人角色" prop="approverNameRole">
          <el-input v-model="form.approverNameRole" placeholder="请输入审批人角色" />
        </el-form-item>
        <el-form-item label="下一个审核人id" prop="nextApproverId">
          <el-input v-model="form.nextApproverId" placeholder="请输入下一个审核人id" />
        </el-form-item>
        <el-form-item label="下一个审核人" prop="nextApprover">
          <el-input v-model="form.nextApprover" placeholder="请输入下一个审核人" />
        </el-form-item>
        <el-form-item label="下一个审核人角色" prop="nextApproverRole">
          <el-input v-model="form.nextApproverRole" placeholder="请输入下一个审核人角色" />
        </el-form-item>
        <el-form-item label="业务id" prop="bussniessId">
          <el-input v-model="form.bussniessId" placeholder="请输入业务id" />
        </el-form-item>
        <el-form-item label="当前操作步骤描述" prop="currentStep">
          <el-input v-model="form.currentStep" placeholder="请输入当前操作步骤描述" />
        </el-form-item>
        <el-form-item label="下一步操作描述" prop="nextStep">
          <el-input v-model="form.nextStep" placeholder="请输入下一步操作描述" />
        </el-form-item>
        <el-form-item label="审核步骤" prop="stepNo">
          <el-input v-model="form.stepNo" placeholder="请输入审核步骤" />
        </el-form-item>
        <el-form-item label="额外字段1" prop="extraField1">
          <el-input v-model="form.extraField1" placeholder="请输入额外字段1" />
        </el-form-item>
        <el-form-item label="额外字段2" prop="extraField2">
          <el-input v-model="form.extraField2" placeholder="请输入额外字段2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Record">
import { listRecord, getRecord, delRecord, addRecord, updateRecord } from "@/api/system/record"
import { useRouter } from 'vue-router'

const router = useRouter()
const { proxy } = getCurrentInstance()

const recordList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: null,
    approverId: null,
    approverName: null,
    nextApproverId: null,
    nextApprover: null,
    bussniessId: null,
    currentStep: null,
    nextStep: null,
    auditStatus: null,
    stepNo: null,
    handleType: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询审批记录列表 */
function getList() {
  loading.value = true
  listRecord(queryParams.value).then(response => {
    // 将数据倒序排列
    recordList.value = response.rows.reverse()
    total.value = response.total
    loading.value = false
    console.log('倒序后的审批记录数据:', recordList.value)
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    opinion: null,
    type: null,
    finishTime: null,
    approverId: null,
    approverName: null,
    approverNameRole: null,
    nextApproverId: null,
    nextApprover: null,
    nextApproverRole: null,
    bussniessId: null,
    currentStep: null,
    nextStep: null,
    auditStatus: null,
    stepNo: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    handleType: null,
    extraField1: null,
    extraField2: null
  }
  proxy.resetForm("recordRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加审批记录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getRecord(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改审批记录"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["recordRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除审批记录编号为"' + _ids + '"的数据项？').then(function() {
    return delRecord(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/record/export', {
    ...queryParams.value
  }, `record_${new Date().getTime()}.xlsx`)
}

/** 查看按钮操作 */
function handleView(row) {
  console.log('========== 查看按钮点击 ==========')
  console.log('完整记录:', row)
  console.log('类型 type:', row.type, '业务ID:', row.bussniessId, '审批状态:', row.auditStatus)
  
  // 根据类型跳转到不同的页面
  if (row.type === 3 || row.type === '3') {
    // 入住申请 - 跳转到入住管理表单页面（只读模式）
    router.push({
      path: '/system/management/checkInForm',
      query: {
        id: row.bussniessId,
        step: row.stepNo || 1,
        type: row.type,
        mode: 'view'
      }
    })
  } else if (row.type === 1 || row.type === '1') {
    // 退住申请
    router.push({
      path: '/splccs/spsq',
      query: {
        id: row.bussniessId,
        step: row.stepNo || 2,
        type: row.type,
        mode: 'view'
      }
    })
  } else if (row.type === 2 || row.type === '2') {
    // 请假申请 - 跳转到第三个页面（审批结果页面）
    console.log('>>> 请假申请，跳转到第三个页面')
    console.log('>>> 业务ID:', row.bussniessId)
    console.log('>>> 不传递状态参数，让页面从数据库查询实际的请假状态')
    
    // 不传递 statusFromRecord 参数，让前端从数据库查询请假申请的实际状态
    // 这样可以确保显示的是请假申请表中的真实状态，而不是审批记录的状态
    router.push({
      path: '/system/sq',
      query: {
        id: row.bussniessId,
        step: 3, // 固定跳转到第三个页面
        type: row.type,
        mode: 'view'
        // 不传递 statusFromRecord，让页面查询数据库中的实际状态
      }
    })
  } else {
    // 默认跳转
    router.push({
      path: '/system/sq',
      query: {
        id: row.bussniessId,
        step: 3,
        type: row.type
      }
    })
  }
  console.log('========== 处理完成 ==========')
}

getList()
</script>
